#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/stat.h>   // mkdir
#include <unistd.h>     // access
#include <errno.h>      // error

#include "../my_inc/user_manager.h"

// 用户数据文件路径
const char *USER_FILE = "./User/users.txt";

// 当前用户根路径
char current_user_path[128];
char user_path[128];

// 检查用户是否存在
bool user_exists(const char *username) {
    FILE *file = fopen(USER_FILE, "r");
    if (!file)
    {
        return false;
    } 
    
    char line[100];
    while (fgets(line, sizeof(line), file)) {
        char saved_username[32];
        if (sscanf(line, "%31[^,],%*s", saved_username) == 1) {
            if (strcmp(saved_username, username) == 0) {
                fclose(file);
                return true;
            }
        }
    }
    
    fclose(file);
    

    return false;
}

// 保存用户信息
bool save_user(const char *username, const char *password) {
    
    
    // 检查用户是否已存在
    if (user_exists(username)) {
        return false;
    }
    
    FILE *file = fopen(USER_FILE, "a");
    if (!file) return false;
    
    fprintf(file, "%s,%s\n", username, password);
    fclose(file);

    /* 确保顶层 UserFile 存在 */
    if (access("/UserFile", F_OK) != 0) {                 // 不存在
        if (mkdir("/UserFile", 0755) != 0) 
        {
            printf("创建目录失败\n");
            return false;  // 创建失败
        }
    }
    /* 创建 /UserFile/username */
    snprintf(user_path, sizeof(user_path), "/UserFile/%s", username);
    if (mkdir(user_path, 0777) != 0 && errno != EEXIST) 
    {
        return false;
    }

    /* 创建 UserFile/username/Screenshot */
    char screenshot_path[256];
    snprintf(screenshot_path, sizeof(screenshot_path), "%s/Screenshot", user_path);
    if (mkdir(screenshot_path, 0777) != 0 && errno != EEXIST) 
    {
        return false;
    }

    return true;
}

// 验证用户
bool authenticate_user(const char *username, const char *password) {
    FILE *file = fopen(USER_FILE, "r");
    if (!file) return false;
    
    char line[100];
    while (fgets(line, sizeof(line), file)) {
        char saved_username[32], saved_password[32];
        if (sscanf(line, "%31[^,],%31s", saved_username, saved_password) == 2) {
            if (strcmp(saved_username, username) == 0 && 
                strcmp(saved_password, password) == 0) {
                fclose(file);
                return true;
            }
        }
    }
    
    fclose(file);
    return false;
}

// 验证两次输入的密码是否一致
bool check_password(const char *password1, const char *password2) {
    if (strcmp(password1, password2) == 0) {
        return true;
    }
    return false;
}
